//
// Created by user on 2022/3/22.
//

#include <vector>
#include <queue>
using namespace std;
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

//队列
vector<vector<int>> levelOrder(TreeNode* root) {
    vector<vector<int>> res;
    if(!root)return res;
    queue<TreeNode*> st;
    st.push(root);
    while (!st.empty()){
        int size  = st.size();
        vector<int> first;
        for (int i=0; i<size; i++){
            TreeNode *currNode = st.front();
            st.pop();
            first.push_back(currNode->val);
            if(currNode->left){st.push(currNode->left);}
            if(currNode->right){st.push(currNode->right);}
        }
        res.push_back(first);
    }
    return res;
}

//堆栈+迭代
#include <stack>
vector<vector<int>> levelOrder1(TreeNode* root) {
    if (!root) return {};
    vector<vector<int>> res;
    stack<pair<TreeNode*, int>> st;
    st.push(make_pair(root, 0));
    while (!st.empty()) {
        pair<TreeNode*, int> curr = st.top();
        st.pop();

        TreeNode * currNode = curr.first;
        int currLevel = curr.second;

        if(res.size()==currLevel){
            vector<int> levelNodes = {currNode->val};
            res.push_back(levelNodes);
        }else{
            res[currLevel].push_back(currNode->val);
        }

        if(currNode->right){
            st.push(make_pair(currNode->right, currLevel+1));
        }
        if(currNode->left){
            st.push(make_pair(currNode->left, currLevel+1));
        }
    }
    return res;
}

//堆栈+递归
void preOrder(TreeNode* node, int currLevel, vector<vector<int>>& res);
vector<vector<int>> levelOrder2(TreeNode* root) {
    if (!root) return {};

    vector<vector<int>> res;
    preOrder(root, 0, res);
    return res;
}

void preOrder(TreeNode* node, int currLevel, vector<vector<int>>& res) {
    if (!node) return;

    if (res.size() == currLevel) {
        vector<int> levelNodes = {node->val};
        res.push_back(levelNodes);
    } else {
        res[currLevel].push_back(node->val);
    }

    preOrder(node->left, currLevel + 1, res);
    preOrder(node->right, currLevel + 1,  res);
}